import 'dart:io';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

class TestWechatImagePicker extends StatefulWidget {
  const TestWechatImagePicker({Key? key}) : super(key: key);

  @override
  _TestWechatImagePickerState createState() => _TestWechatImagePickerState();
}

class _TestWechatImagePickerState extends State<TestWechatImagePicker> {
  List<AssetEntity> images = <AssetEntity>[];
  String _error = 'No Error Dectected';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Plugin example app'),
      ),
      body: Column(
        children: <Widget>[
          ElevatedButton(
            onPressed: _getPermission,
            child: const Text("getPermission"),
          ),
          Center(child: Text('Error: $_error')),
          ElevatedButton(
            onPressed: _loadAssets,
            child: const Text("Pick images"),
          ),
          Expanded(
            child: _buildGridView(),
          )
        ],
      ),
    );
  }

  Future<void> _getPermission() async {
    // final deviceInfo = await DeviceInfoPlugin().androidInfo;
    // if (deviceInfo.version.sdkInt > 32) {
    //   permission = Permission.photos;
    // } else {
    //   permission = Permission.storage;
    // }

    var status = await Permission.storage.request();
    if (status.isDenied) {
      print("dont have photo permission");
    } else {
      print("have photo permission");
    }
  }

  Widget _buildGridView() {
    return GridView.count(
      crossAxisCount: 3,
      children: List.generate(images.length, (index) {
        AssetEntity asset = images[index];
        return AssetEntityImage(
          asset,
          width: 300,
          height: 300,
        );
      }),
    );
  }

  Future<void> _loadAssets() async {
    final List<AssetEntity>? result = await AssetPicker.pickAssets(
      context,
      pickerConfig: const AssetPickerConfig(),
    );

    result?.forEach((AssetEntity asset) async {
      print('Selected asset: ${asset.id} ${asset.relativePath} ');
      File? file = await asset.file;
      print(file?.path);
    });

    setState(() {
      images = result ?? [];
    //   _error = error;
    });
  }
}
